package org.dynamo.database.ui.wizzard.launcher;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.List;

import org.dynamo.database.ui.wizzard.DTUImage;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IAdapterFactory;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.dialogs.SelectionStatusDialog;
import org.eclipse.ui.model.BaseWorkbenchContentProvider;
import org.eclipse.ui.model.IWorkbenchAdapter;
import org.eclipse.ui.model.WorkbenchLabelProvider;

public class SelectFileDiag extends SelectionStatusDialog {

	private String path;
	private String platformFile;
	private Text textFile;
	private Image logo;
	private IAdapterFactory adapterFactory = new FileAdapterFactory();

	public SelectFileDiag(Shell parent) {
		super(parent);
	}

	public SelectFileDiag(Shell parent, String file) {
		this(parent);
		platformFile = file;
	}

	public String getSelectedFile() {
		return platformFile;
	}

	protected Control createDialogArea(Composite parent) {
		logo = DTUImage.IMG_DTU.createImage();
		Composite container = new Composite(parent, SWT.NONE);
		container.setLayout(new GridLayout(1, true));
		GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
		data.minimumHeight = 400;
		container.setLayoutData(data);

		textFile = new Text(container, SWT.BORDER);
		textFile.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false));
		textFile.setEnabled(false);

		TreeViewer treeViewer = new TreeViewer(container, SWT.BORDER
				| SWT.MULTI | SWT.V_SCROLL);
		Platform.getAdapterManager().registerAdapters(adapterFactory,
				File.class);
		path = ResourcesPlugin.getWorkspace().getRoot().getLocation()
				.toString();
		treeViewer.setLabelProvider(new WorkbenchLabelProvider());
		treeViewer.setContentProvider(new BaseWorkbenchContentProvider());
		treeViewer.setInput(new File(path));
		treeViewer.getTree().setLayoutData(
				new GridData(SWT.FILL, SWT.FILL, true, true));
		treeViewer.addSelectionChangedListener(new ISelectionChangedListener() {
			public void selectionChanged(SelectionChangedEvent event) {
				String strFile = "";
				if (event.getSelection().isEmpty()) {
					textFile.setText("");
					return;
				}
				if (event.getSelection() instanceof IStructuredSelection) {
					IStructuredSelection selection = (IStructuredSelection) event
							.getSelection();
					if (selection.iterator().hasNext()) {
						File file = (File) selection.iterator().next();
						strFile = file.getPath().substring(path.length());
					}
				}
				textFile.setText(strFile);
			}
		});

		if (platformFile != "") {
			treeViewer
					.setSelection(getFileSelection(path + platformFile), true);
		}

		return container;
	}

	private StructuredSelection getFileSelection(String filename) {
		File file = new File(filename);
		List<File> filepath = new ArrayList<File>();
		filepath.add(file);
		File parent = file;
		File stop = new File(path);
		do {
			parent = parent.getParentFile();
			if (parent != null) {
				if (stop.getPath().equals(parent.getPath()))
					break;
				filepath.add(parent);
			}
		} while (parent != null);

		List<File> filetab = new ArrayList<File>();
		for (int i = filepath.size() - 1; i >= 0; i--) {
			filetab.add(filepath.get(i));
		}
		return new StructuredSelection(new TreePath(filetab.toArray()));
	}

	@Override
	protected void computeResult() {
		platformFile = textFile.getText();
	}

	private class FileAdapterFactory implements IAdapterFactory {

		public FileAdapterFactory() {
			super();
		}

		private IWorkbenchAdapter fileContentAdapter = new IWorkbenchAdapter() {

			public Object getParent(Object o) {
				return ((File) o).getParent();
			}

			public String getLabel(Object o) {
				return ((File) o).getName();
			}

			public ImageDescriptor getImageDescriptor(Object object) {
				if (object instanceof File) {
					File file = (File) object;
					if (file.isDirectory()) {
						return DTUImage.IMG_FOLDER;
					} else if (file.isFile() && file.getName().endsWith(".dtu")) {
						return DTUImage.IMG_DTU;
					}
				}
				return DTUImage.IMG_PAGE_OBJ;
			}

			public Object[] getChildren(Object o) {
				Object[] kids = ((File) o).listFiles(new FileFilter() {
					
					@Override
					public boolean accept(File pathname) {
						if(pathname.isDirectory())
						{
							return true;
						} else if(pathname.getAbsolutePath().endsWith(".dtu"))
						{
							return true;
						}
						return false;
					}
				});
				return kids == null ? new Object[0] : kids;
			}
		};

		@SuppressWarnings("unchecked")
		public Object getAdapter(Object adaptableObject, Class adapterType) {
			if (adapterType == IWorkbenchAdapter.class
					&& adaptableObject instanceof File)
				return fileContentAdapter;
			return null;
		}

		@SuppressWarnings("unchecked")
		public Class[] getAdapterList() {
			return new Class[] { IWorkbenchAdapter.class };
		}
	}

	public String getPlatformFile() {
		return platformFile;
	}
	
	public Image getImage()
	{
		return logo;
	}
}
